/*
' DotNetNuke?- http://www.dotnetnuke.com
' Copyright (c) 2002-2006
' by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
' DEALINGS IN THE SOFTWARE.
 */

using System;

using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using System.Net;
using System.IO;
using System.Xml;
using System.Web.UI.WebControls;
using System.Collections.Generic;

namespace YourCompany.Modules.TweetNuke
{
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The EditTweetNuke class is used to manage content
    /// </summary>
    /// <remarks>
    /// </remarks>
    /// <history>
    /// </history>
    /// -----------------------------------------------------------------------------
    partial class EditTweetNuke : PortalModuleBase
    {

    #region Private Members

        private int ItemId = Null.NullInteger;

    #endregion

    #region Event Handlers

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            try
            {
                //Determine ItemId of TweetNuke to Update
                if(this.Request.QueryString["ItemId"] !=null)
                {
                    ItemId = Int32.Parse(this.Request.QueryString["ItemId"]);
                }

                //If this is the first visit to the page, bind the role data to the datalist
                if (Page.IsPostBack == false)
                {
                    cmdDelete.Attributes.Add("onClick", "javascript:return confirm('" + Localization.GetString("DeleteItem") + "');");

                    if(ItemId != -1)
                    {
                        //get content
                        TweetNukeController objTweetNukes = new TweetNukeController();
                        TweetNukeInfo objTweetNuke = objTweetNukes.GetTweetNuke(ModuleId,ItemId);
                        if (objTweetNuke != null)
                        {
                            txtUsername.Text = objTweetNuke.Username;
                            txtPassword.Attributes.Add("value", objTweetNuke.Password);
                            string followingsString = objTweetNuke.FollowingsCache;
                            
                            if (objTweetNuke.TweetsToDisplay != 0)
                            {
                                txtTweetsToDisplay.Text = objTweetNuke.TweetsToDisplay.ToString();
                            }
                            List<string> selected = stringToList(objTweetNuke.FollowingsToDisplay);
                            Dictionary<string, string> followingsDictionary = stringToDictionary(objTweetNuke.FollowingsCache);
                            if (objTweetNuke.Username != "" & objTweetNuke.Password != "")
                            {
                                XmlNodeList followings = getFollowings(objTweetNuke);
                                if (followings != null && followings.Count > 0)
                                {
                                    foreach (XmlNode id in followings)
                                    {
                                          ListItem li = new ListItem();
                                          li.Value = id.InnerText;
                                          try
                                          {
                                              if (followingsDictionary.ContainsKey(id.InnerText))
                                              {
                                                  li.Text = followingsDictionary[id.InnerText];
                                              }
                                              else
                                              {
                                                  li.Text = getScreenName(id.InnerText);
                                                  followingsDictionary.Add(id.InnerText, li.Text);
                                              }
                                              if (selected.Contains(id.InnerText))
                                              {
                                                  li.Selected = true;
                                              }
                                            lbxFollowings.Items.Add(li);
                                          }
                                          catch (Exception ex) { }
                                    }
                                    lbxFollowings.Visible = true;
                                    lblFollowings.Visible = true;
                                    hdnFollowings.Value = dictionaryToString(followingsDictionary);
                                }
                            }
                        }
                        else
                        {
                            Response.Redirect(Globals.NavigateURL(), true);
                        }
                    }
                    else
                    {
                        cmdDelete.Visible = false;
                    }
                }
           }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }            
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdCancel_Click runs when the cancel button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void cmdCancel_Click(System.Object sender, System.EventArgs e)
        {
            try
            {
                this.Response.Redirect(Globals.NavigateURL(this.TabId), true);
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdDelete_Click runs when the delete button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void cmdDelete_Click(System.Object sender, System.EventArgs e)
        {
            try
            {
                //Only attempt to delete the item if it exists already
                if (!Null.IsNull(ItemId))
                {
                    TweetNukeController objTweetNukes = new TweetNukeController();
                    objTweetNukes.DeleteTweetNuke(ModuleId,ItemId);
 
                    //refresh cache
                    ModuleController.SynchronizeModule(ModuleId);
                }

                this.Response.Redirect(Globals.NavigateURL(this.TabId), true);
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdUpdate_Click runs when the update button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void cmdUpdate_Click(System.Object sender, System.EventArgs e)
        {
            try
            {
                ListItemCollection listItems = lbxFollowings.Items;
                string selected = "";
                foreach (ListItem li in listItems)
                {
                    if (li.Selected)
                    {
                        selected += li.Value + ";";
                    }
                }
                if (selected.Length > 0)
                {
                    selected = selected.Substring(0, selected.Length - 1);
                }
                TweetNukeController objTweetNukes = new TweetNukeController();
                TweetNukeInfo objTweetNuke = new TweetNukeInfo();

                objTweetNuke.ModuleId = ModuleId;
                objTweetNuke.ItemId = ItemId;
                objTweetNuke.Username = txtUsername.Text;
                objTweetNuke.Password = txtPassword.Text;
                if (txtTweetsToDisplay.Text != "")
                {
                    try
                    {
                        objTweetNuke.TweetsToDisplay = int.Parse(txtTweetsToDisplay.Text);
                    }
                    catch (Exception ex) { }
                }
                if (objTweetNuke.Username != "" & objTweetNuke.Password != "")
                {
                    objTweetNuke.FollowingsToDisplay = selected;
                }
                else
                {
                    objTweetNuke.FollowingsToDisplay = "";
                }
                
                objTweetNuke.FollowingsCache = hdnFollowings.Value;
                //Update the content within the TweetNuke table
                if(Null.IsNull(ItemId))
                {
                    objTweetNukes.AddTweetNuke(objTweetNuke);
                }
                else
                {
                    objTweetNukes.UpdateTweetNuke(objTweetNuke);
                }

                //refresh cache
                ModuleController.SynchronizeModule(ModuleId);

                if (lbxFollowings.Visible)
                {
                    //Redirect back to the portal home page
                    this.Response.Redirect(Globals.NavigateURL(this.TabId), true);
                }
                else
                {
                    //Refresh current edit page
                    this.Response.Redirect(Request.Url.AbsoluteUri, true);
                }
             }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

    #endregion

    #region Twitter function
      private XmlNodeList getFollowings(TweetNukeInfo objTweetNuke)
      {
        string url = "http://twitter.com/friends/ids.xml";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.ServicePoint.Expect100Continue = false;
        request.Credentials = new NetworkCredential(objTweetNuke.Username, objTweetNuke.Password);
        try
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
            string xmlString = sr.ReadToEnd();
            sr.Close();
            response.Close();

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(new StringReader(xmlString));
            return xmlDoc.GetElementsByTagName("id");
        }
        catch (Exception ex)
        {
            return null;
        }
      }

      private string getScreenName(string id)
      {
        string url = "http://twitter.com/users/show.xml?user_id=" + id;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.ServicePoint.Expect100Continue = false;
        
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
        string xmlString = sr.ReadToEnd();
        sr.Close();
        response.Close();

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(new StringReader(xmlString));
        return xmlDoc.GetElementsByTagName("screen_name").Item(0).InnerText;
      }

        private Dictionary<string, string> stringToDictionary(string followingsString)
        {
            Dictionary<string, string> followingsDictionary = new Dictionary<string,string>();
            string[] followingsArray = followingsString.Split(';');
            foreach (string s in followingsArray)
            {
                string[] array = s.Split('=');
                if (array.Length == 2 && !followingsDictionary.ContainsKey(array[0]))
                {
                    followingsDictionary.Add(array[0], array[1]);
                }
            }
            return followingsDictionary;
        }

        private string dictionaryToString(Dictionary<string, string> followingsDictionary)
        {
            string followingsString = "";
            foreach (KeyValuePair<string, string> pair in followingsDictionary)
            {
                followingsString += pair.Key + "=" + pair.Value + ";";
            }
            if (followingsString.Length > 0)
            {
                followingsString = followingsString.Substring(0, followingsString.Length - 1);
            }
            return followingsString;
        }

        private List<string> stringToList(string selectedFollowings)
        {
            string[] selectedArray = selectedFollowings.Split(';');
            List<string> selectedList = new List<string>(selectedArray.Length);
            selectedList.AddRange(selectedArray);
            return selectedList;
        }


    #endregion

    }
}

